import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfoAPI, getUserProfileAPI } from '@/API/userAPI.js'
Vue.use(Vuex)

// 初始化state里的数据 以一个变量的形式定义
let initState = {
  tokenInfo: {}, // token信息
  userInfo: {}, // 用户基本信息
  useProfile: {} // 用户简介信息
}
// 从storage中取到的对象保存给一个常量
const stateStr = JSON.parse(localStorage.getItem('state'))
// 判断 如果取到值 那么就赋值给初始化state的数据里,如果没有那么就还是一个空对象
if (stateStr) {
  initState = stateStr
}

export default new Vuex.Store({
  state: initState,
  mutations: {
    updateTokenInfo (state, payload) {
      // payload是从主组件发送过来的token和refresh token数据 是一个对象形式
      state.tokenInfo = payload
      // 一个mutation方法调用另一个mutation需要commit来调用
      this.commit('saveStateToStorage')
    },
    // 把数据存放在localStorage中,封装成一个方法,在数据发生更新时调用
    saveStateToStorage (state) {
      localStorage.setItem('state', JSON.stringify(state))
    },
    // 把获取的用户信息存放到state中
    updateUserInfo (state, payload) {
      state.userInfo = payload
      this.commit('saveStateToStorage') // 把获取到的用户信息也要储存到本地
    },
    // 退出登录清空state
    clearState (state) {
      state.tokenInfo = {}
      state.userInfo = {}
      state.useProfile = {}
      this.commit('saveStateToStorage') // 清空后存储到本地
    },
    // 把获取的用户简介信息存储到state中
    updateUserProfile (state, payload) {
      // console.log(payload)
      state.useProfile = payload
      this.commit('saveStateToStorage')
    }
  },
  actions: {
    // 获取用户基本信息
    async  getUserInfo (ctx) {
      const { data: res } = await getUserInfoAPI()
      if (res.message === 'OK') {
        // console.log(res)
        ctx.commit('updateUserInfo', res.data)
      }
    },
    // 获取用户简介信息
    async  getUserProfile (ctx) {
      const { data: res } = await getUserProfileAPI()
      if (res.message === 'OK') {
        // console.log(res)
        ctx.commit('updateUserProfile', res.data)
      }
    }

  },
  getters: {
    userAvatar (state) {
      // 默认图片地址
      let images = 'https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%A4%A7%E5%8F%B8%E9%A9%AC%E5%A4%B4%E5%83%8F&hs=2&pn=1&spn=0&di=65120&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&ie=utf-8&oe=utf-8&cl=2&lm=-1&cs=114525244%2C2994967292&os=1698209274%2C2486950651&simid=0%2C0&adpicid=0&lpn=0&ln=30&fr=ala&fm=&sme=&cg=&bdtype=0&oriquery=%E5%A4%A7%E5%8F%B8%E9%A9%AC%E5%A4%B4%E5%83%8F&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Ffjmingfeng.com%2Fimg%2F0%2F0089119851%2F62%2F12dfe077a72cc9ae06382251fd66f8ca%2F9400327224%2F9095658571.jpg%26refer%3Dhttp%3A%2F%2Ffjmingfeng.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1621819624%26t%3De6e5235d7110093099e97383e08dd9d9&fromurl=ippr_z2C%24qAzdH3FAzdH3Fu34tg2ujg2_z%26e3Bv54AzdH3F7g4zrAzdH3Fzk9zunzvkzkjzvdzj1zvdzj1zvazvuzvwzwmzv1zk0zvuzu8_z%26e3Bip4&gsm=2&islist=&querylist='
      if (state.userInfo.photo) {
        images = state.userInfo.photo
      }
      return images
    }
  },
  modules: {
  }
})
